package com.wenwen.social.application.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wenwen.social.application.MessageApplication;
import com.wenwen.social.application.dto.MdataDTO;
import com.wenwen.social.application.event.MessageCreateEvent;
import com.wenwen.social.application.event.MessageDelEvent;
import com.wenwen.social.domain.model.Mdata;
import com.wenwen.social.domain.model.Medias;
import com.wenwen.social.domain.model.Message;
import com.wenwen.social.domain.model.User;
import com.wenwen.social.domain.service.MessageService;
import com.wenwen.social.domain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.wenwen.social.constant.MessageConstant.VALID;
import static com.wenwen.social.util.IdUtil.getMessageId;
import static java.util.stream.Collectors.toList;

@Service
public class MessageApplicationImpl implements MessageApplication {

	@Autowired
	private MessageService messageService;
	@Autowired
	private UserService userService;

	/**
	 * 给监听器用
	 */
	@Autowired
	ApplicationContext applicationContext;

	public Long createMessage(Long userId, String msg, Integer mediaType, List<MdataDTO> list){
		if(mediaType == null){
			mediaType =0;
		}
		User user = userService.getUser(userId);
		if(user == null) return 0L;
		Long now = System.currentTimeMillis();
		List<Mdata> newList = convertMdata(list);
		Medias medias = new Medias();
		if(newList != null && !newList.isEmpty()){
			medias = new Medias(newList,0);
			medias.setMdatas(newList);
			medias.setVersion(0);
		}
		Long messageId = getMessageId();
		Message message = new Message(messageId,msg,userId,now,VALID,mediaType,medias);
		messageService.add(message);
		applicationContext.publishEvent(new MessageCreateEvent(this,message));
		return messageId;
	}

	private List<Mdata> convertMdata(List<MdataDTO> list) {
		return list.stream().filter(t -> t != null).map(t -> {
			Mdata mdata = new Mdata();
			BeanUtil.copyProperties(t, mdata);
			return mdata;
		}).collect(toList());
	}

	public Integer delMessage(Long uid,Long msgId){
		User user = userService.getUser(uid);
		if(user == null) return 0;
		Message message = new Message(msgId, null, uid, null, null, null, null);
		Integer del = messageService.del(message);
		if(del > 0){
			applicationContext.publishEvent(new MessageDelEvent(this,message));
			return 1;
		}
		return 0;
	}
}
